#include "mqtthandler.h"
#include <QTimer>
#include <qmqtt_client.h>



MqttHandler::MqttHandler(QObject *parent) : QObject(parent)
{
    client = new QMQTT::Client();
    client->setClientId("home-app");

    connect(client, SIGNAL(connected()), this, SLOT(doConnected()));

    connect(client, SIGNAL(subscribed(QString, quint8)),\
            this, SLOT(doSubscribed(QString, quint8)));

    connect(client,SIGNAL(received(QMQTT::Message)),\
            this,SLOT(doDataReceived(QMQTT::Message)));
}

void MqttHandler::connectToHost()
{
    client->connectToHost();

    //3s后检测一下连接状态
    QTimer::singleShot(3000, this, SLOT(detectState()));
}

void MqttHandler::detectState()
{
    int state = client->connectionState();
    if(state != 2)  //STATE_CONNECTED引用不到，很奇怪
    {
        qDebug()<<"mqtt connect error";
    }
}

/**
 * @brief 连接以后再订阅相关的主题
 */
void MqttHandler::doConnected()
{
    qDebug()<<"connect ok";
    client->subscribe(TOPIC_DATA_UP);
    client->subscribe(TOPIC_CTL_UP);

    emit connected();  // 发射连接成功信号
}

void MqttHandler::doSubscribed(const QString& topic, const quint8 qos)
{
    qDebug()<<"subscribed ok, topic="<<topic;
}

void MqttHandler::doDataReceived(QMQTT::Message message)
{
    qDebug()<<"topic="<<QString(message.topic());
    qDebug()<<"payload="<<QString(message.payload());

    if(message.topic() == TOPIC_DATA_UP){
        qDebug()<<"data up topic";
        emit dataUpSignal(message.payload());
    }else if(message.topic() == TOPIC_CTL_UP){
        qDebug()<<"ctrl up topic";
        emit ctrlUpSignal(message.payload());
    }
}

quint16 MqttHandler::publish(const QMQTT::Message &message)
{
    client->publish(message);
}
